package com.k2data.k2app.service;

import com.google.common.collect.Lists;
import com.k2data.k2app.common.ExecutorManager;
import com.k2data.k2app.common.MyConstant;
import com.k2data.k2app.domain.po.DictPO;
import com.k2data.k2app.mapper.CustomerMapper;
import com.k2data.k2app.rest.SysClient;
import com.k2data.k2app.rest.domain.DictRest;
import com.k2data.k2app.rest.domain.DictResult;
import com.k2data.k2app.utils.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * @author lidong9144@163.com 17-3-20.
 */
@Service
public class ConditionService {

    private final SysClient sysClient;

    private final CustomerMapper customerMapper;

    @Autowired
    public ConditionService(CustomerMapper customerMapper, SysClient sysClient) {
        this.customerMapper = customerMapper;
        this.sysClient = sysClient;
    }

    public Map<String, List<DictPO>> getCondition(List<String> types) throws InterruptedException {
        ConcurrentHashMap<String, List<DictPO>> map = new ConcurrentHashMap<>();

        if (ObjectUtils.isEmpty(types)) {
            return map;
        }

        CountDownLatch latch = new CountDownLatch(types.size());

        for (String type : types) {
            if (MyConstant.COND_CUSTOMER_NO.equals(type)) {
                ExecutorManager.submit(() -> {
                    map.put(MyConstant.COND_CUSTOMER_NO, customerMapper.selectCustomerNoCondition());
                    latch.countDown();
                });
                continue;
            }

            ExecutorManager.submit(() -> {
                DictRest rest = sysClient.get(type);
                List<DictPO> list = Lists.newArrayList();
                for (DictResult dictResult : rest.getResult()) {
                    DictPO dict = new DictPO();
                    dict.setLabel(dictResult.getLabel());
                    dict.setValue(dictResult.getValue());
                    list.add(dict);
                }
                map.put(type, list);
                latch.countDown();
            });
        }

        latch.await();

        return map;
    }

}
